# -*- coding: utf-8 -*-
#
# GmAnt
# http://www.royalar.cn/2009/11/gmant
#
import sys
from GmAnt import *
import cmd
import getopt
reload(sys)
sys.setdefaultencoding('utf8')

gmant = GmAnt()

class CLI(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        print u'welcome,type h for help'
        self.cachealbum = {}
        self.cacheartist = {}
        self.cachealbumlist = {}
        self.cachesearch = {}
        self.cachesearchkey = ''
        self.cachesearchtotal = 0


    def default(self, line):
        if line:
            print u' unsupport command:', line
        print

    def do_h(self,args):
        print u'al 查看歌手库'
        print u's  搜索'
        print u'q  退出'


    def do_q(self, arg):
        print 'bye'
        sys.exit(0)

    def do_s(self,args):
        self.cachesearch = ''
        self.cachesearchkey = ''
        self.cachesearchtotal = 0
        ret = gmant.search(args)
        if ret[1] > 0:
            print 'find',ret[1],'albums  keyword is',args
            self.cachesearch = ret[0]
            self.cachesearchtotal = ret[1]
            self.cachesearchkey = args
            album = self._output(self.cachesearch,'',self._s_n,self._s_p,0,ret[1])
            if album:
                self.cachealbum = album
                return self._album(album)
        return

    def _s_n(self,pos,count):
        ret = gmant.search(self.cachesearchkey,pos)
        self.cachesearch += ret[0]
        album = self._output(self.cachesearch,'',self._s_n,'',pos,ret[1])
        if album:
            self.cachealbum = album
            self._album(album)


    def _s_p(self,pos,count):
        pos /= 10
        pos *= 10
        pos -= 10
        if pos < 0: pos = 0
        ret = gmant.search(self.cachesearchkey,pos)
        self.cachesearch += ret[0]
        album = self._output(self.cachesearch,'',self._s_n,'',pos,ret[1])
        if album:
            self.cachealbum = album
            self._album(album)

    def do_cs(self,args):
        if self.cachesearch:
            album = self._output(self.cachesearch,'search cache albumns',self._s_n,self._s_p,0,self.cachesearchtotal)
            if album:
                self.cachealbum = album
                return self._album(album)
            

    def do_ca(self,args):
        if len(self.cachealbumlist) > 0:
            self._artist('')
        else:
            print 'empty album list cache!'

    def do_cache(self,args):
        if self.cacheartist:
            print 'current artist:',self.cacheartist['name'],
            if self.cachealbumlist:
                print ', with',len(self.cachealbumlist),'albums . type ca to list'
        else:
            print 'no cache'

    def do_al(self, args):
        optlist, keys = self._get_opt(args, 't:r:')
        if optlist == False:
            return
        params = { 'type':'female','region':'cn' }
        for opt in optlist:
            if opt[0] == '-t':
                params['type'] = opt[1]
            elif opt[0] == '-r':
                params['region'] = opt[1]
        links = gmant.artistlibrary(params, keys[0]  if len(keys)>0 else '')
        while True:
            artist = self._output(links,u'歌手')
            if artist == False:
                break;
            else:
                self.cacheartist = artist
                return self._artist(artist)
        return

    def _artist(self,id):
        if len(id) ==0:
            links = self.cachealbumlist
        else:
            links = gmant.artist(id)
            self.cachealbumlist = links
        while True:
            album = self._output(links, u'专辑')
            if album == False:
                break;
            else:
                self.cachealbum = album
                return self._album(album)
        return False

    def _album(self,args):
        songs = gmant.album(args)
        if songs == False:
            print gmant.get_msg()
        i=1
        for song in songs:
            print ' %4d %s' % (i,song['name'])
            i+=1
        x=raw_input(u'type \'d\' to download album:')
        if x == 'd':
            gmant.dl_album(self.cachealbum,self.cacheartist,songs)
            print 'download finish'
        return False


    def _get_opt(self, args, options):
        try:
            optlist, left = getopt.getopt(args.split(), options)
        except getopt.GetoptError, err:
            print str(err)
            return (False, False)
        return (optlist, left)

    def _output(self,links,type='',fun_n='',fun_p='',start=0,total=0):
        if total > 0:
            count = total
        else:
            count = len(links)
        if type:
            print count,type
        i = start
        while i<count:
            m = i+10
            if m > count:
                m = count
            for i in xrange(i,m):
                link = links[i]
                print ' %4d %s' % ((i+1),link['name'])
            while True:
                x=raw_input('')
                if x == 'n':
                    i += 1
                    if count<=i:
                        print u'没有下一页'
                        continue
                    if fun_n:
                        fun_n(i,count)
                        return False
                    else:
                        break
                elif x == 'p':
                    if i<=9:
                        print u'没有前一页'
                        continue
                    if fun_p:
                        fun_p(i,count)
                        return False
                    else:
                        i /= 10
                        i *= 10
                        i -= 10
                        if i < 0:i=0
                        break
                elif x == 'q':
                    return False
                else:
                    try:
                        id=int(x)-1
                        if id>=0 and id<count:
                            return links[id]
                    except Exception,e:
                        return False
        return False

